package cs342.project1.mathNotebook.xml;

import java.io.*;
import java.util.Collection;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;

import cs342.project1.mathNotebook.notebook.NotebookEntry;

/**
 * Provides the ability to write notebook entries to a data source
 * @author Gabrielle DuBois
 */
public class DESWriter extends NotebookWriter {
	private CompressionWriter compressWriter;
	private byte[] desKeyData;


    /**
     * Initializes outputstream
     * @param outStream a ByteArrayOutputStream which will be containing info
     * @param userKey a byte[] to be used to enycpt the data
     */
    public DESWriter (ByteArrayOutputStream outStream, byte[] userKey){
		super(outStream);
		desKeyData = userKey;
	}//constructor

    /**
     * @see cs342.project1.mathNotebook.xml.NotebookWriter#saveStream(java.util.Collection)
     */
    public ByteArrayOutputStream saveStream(final Collection<NotebookEntry> entries) {
    	compressWriter = new CompressionWriter( new ByteArrayOutputStream() );

		//uncompressed "file"
		byte[] comBytes = compressWriter.saveStream(entries).toByteArray();
		compressWriter.close();

    	try {
            InputStream in = new ByteArrayInputStream( comBytes );
            out = new ByteArrayOutputStream();

            // Create a key
            //byte[] desKeyData = userKey.getBytes();
            DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey desKey = keyFactory.generateSecret(desKeySpec);

            // Use Data Encryption Standard cipher
            Cipher des = Cipher.getInstance("des");
            des.init(Cipher.ENCRYPT_MODE, desKey);

            byte[] input = new byte[64];
            while (true) {
                int bytesRead = in.read(input);
                if (bytesRead == -1) break;
                byte[] output = des.update(input, 0, bytesRead);
                if (output != null) out.write(output);
            }//while(true)

            byte[] output = des.doFinal();

			//Write to outputStream
            if (output != null)
            	out.write(output);
            in.close();

        }//try
        catch (InvalidKeySpecException e) {
        	System.err.println(e);
            e.printStackTrace();
        }
        catch (InvalidKeyException e) {
        	System.err.println(e);
        }
        catch (NoSuchAlgorithmException e) {
            System.err.println(e);
        }//catch
        catch (NoSuchPaddingException e) {System.err.println(e);}
        catch (BadPaddingException e) {System.err.println(e);}
        catch (IllegalBlockSizeException e) {System.err.println(e);}
        catch (IOException e) {System.err.println(e);}

		return out;
    }//saveStream()

}//DESWriter
